package org.home.millionaire;

import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Game extends Activity implements OnClickListener {
	TextView lblQuestion;
	TextView lblCountDown;
	TextView lblCurTotalAmount;

	Button btn5050;
	Button btnCallFriend;
	Button btnAskGuest;
	Button btnStopGame;

	Button btnAnswerA;
	Button btnAnswerB;
	Button btnAnswerC;
	Button btnAnswerD;
	SharedPreferences prefs;

	int playerTime = 2; // minute
	MyCount counter;

	int tmpTrueAnswer = -1;

	ArrayList<Integer> listLblReward = new ArrayList<Integer>();
	TextView lblRewardTmp;
	int tmpReward = -1;

	MediaPlayer player;
	MediaPlayer player_clock;

	// use for 50:50
	ArrayList<Button> listBtnAnswer = new ArrayList<Button>();
	int removeBtn1 = -1;
	int removeBtn2 = -1;

	ArrayList<Integer> listQuestionUsed = new ArrayList<Integer>();

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (player_clock != null) {
			player_clock.stop();
		}
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (player_clock != null) {
			player_clock.stop();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (player_clock != null && !player_clock.isPlaying()) {
			try {
				player_clock.prepare();
				player_clock.start();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game);

		prefs = PreferenceManager.getDefaultSharedPreferences(Game.this);
		initControl();
		initCountDownTimer();
		firstGenReward();
		genQuestion();
		genActionBtnListener();
		playMusic(R.drawable.music_mini);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		if (v.getId() == tmpTrueAnswer) {
			trueAnswer();
		} else {
			falseAnswer();
		}
	}

	private void initControl() {
		lblQuestion = (TextView) findViewById(R.id.lblQuestion);
		lblCountDown = (TextView) findViewById(R.id.lblCountDown);
		lblCurTotalAmount = (TextView) findViewById(R.id.lblCurTotalAmount);

		btn5050 = (Button) findViewById(R.id.btn5050);
		btnCallFriend = (Button) findViewById(R.id.btnCallFriend);
		btnAskGuest = (Button) findViewById(R.id.btnAskGuest);
		btnStopGame = (Button) findViewById(R.id.btnStopGame);

		btnAnswerA = (Button) findViewById(R.id.btnAnswerA);
		btnAnswerB = (Button) findViewById(R.id.btnAnswerB);
		btnAnswerC = (Button) findViewById(R.id.btnAnswerC);
		btnAnswerD = (Button) findViewById(R.id.btnAnswerD);

		btnAnswerA.setOnClickListener(this);
		btnAnswerB.setOnClickListener(this);
		btnAnswerC.setOnClickListener(this);
		btnAnswerD.setOnClickListener(this);

		listBtnAnswer.add(btnAnswerA);
		listBtnAnswer.add(btnAnswerB);
		listBtnAnswer.add(btnAnswerC);
		listBtnAnswer.add(btnAnswerD);

		if (prefs.getBoolean("checkbox_sound", true)) {
			player_clock = MediaPlayer.create(this, R.drawable.clock);
			player_clock.setLooping(true);
			player_clock.setVolume(100, 100);
			player_clock.start();
		}
	}

	private void genActionBtnListener() {
		btn5050.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				do {
					removeBtn1 = (new Random().nextInt(listBtnAnswer.size()));
					removeBtn2 = (new Random().nextInt(listBtnAnswer.size()));
				} while (removeBtn1 == removeBtn2
						|| tmpTrueAnswer == listBtnAnswer.get(removeBtn1)
								.getId()
						|| tmpTrueAnswer == listBtnAnswer.get(removeBtn2)
								.getId());

				listBtnAnswer.get(removeBtn1).setVisibility(View.INVISIBLE);
				listBtnAnswer.get(removeBtn2).setVisibility(View.INVISIBLE);
				btn5050.setVisibility(View.INVISIBLE);
			}
		});

		btnCallFriend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getBaseContext(),
						Game_CallFriend.class);
				startActivity(intent);
				btnCallFriend.setVisibility(View.INVISIBLE);
			}
		});

		btnAskGuest.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int percentGetTrueAnswerLevel1_From = 45;
				int percentGetTrueAnswerLevel1_To = 90;
				int percentGetTrueAnswerLevel2_From = 40;
				int percentGetTrueAnswerLevel2_To = 80;
				int percentGetTrueAnswerLevel3_From = 30;
				int percentGetTrueAnswerLevel3_To = 70;

				int percentGetTrueAnswerLevel1_2_From = 55;
				int percentGetTrueAnswerLevel1_2_To = 100;
				int percentGetTrueAnswerLevel2_2_From = 50;
				int percentGetTrueAnswerLevel2_2_To = 85;
				int percentGetTrueAnswerLevel3_2_From = 40;
				int percentGetTrueAnswerLevel3_2_To = 75;

				int trueAnswer = 0;
				int otherAnswer1 = 0;
				int otherAnswer2 = 0;
				int otherAnswer3 = 0;

				String trueAns = ((Button) findViewById(tmpTrueAnswer))
						.getText().toString().split("\\.")[0];
				String guestAns;
				if (removeBtn1 == -1 && removeBtn2 == -1) {
					if (tmpReward < 5) {
						trueAnswer = new Random()
								.nextInt(percentGetTrueAnswerLevel1_To
										- percentGetTrueAnswerLevel1_From + 1)
								+ percentGetTrueAnswerLevel1_From;
					} else if (tmpReward < 10) {
						trueAnswer = new Random()
								.nextInt(percentGetTrueAnswerLevel2_To
										- percentGetTrueAnswerLevel2_From + 1)
								+ percentGetTrueAnswerLevel2_From;
					} else if (tmpReward < 15) {
						trueAnswer = new Random()
								.nextInt(percentGetTrueAnswerLevel3_To
										- percentGetTrueAnswerLevel3_From + 1)
								+ percentGetTrueAnswerLevel3_From;
					}

					otherAnswer1 = new Random().nextInt(100 - trueAnswer);
					otherAnswer2 = new Random().nextInt(100 - trueAnswer
							- otherAnswer1);
					otherAnswer3 = 100 - trueAnswer - otherAnswer1
							- otherAnswer2;

					if (trueAns.equals("A"))
						guestAns = "A: " + trueAnswer + "%\n" + "B: "
								+ otherAnswer1 + "%\n" + "C: " + otherAnswer2
								+ "%\n" + "D: " + otherAnswer3 + "%";
					else if (trueAns.equals("B"))
						guestAns = "A: " + otherAnswer1 + "%\n" + "B: "
								+ trueAnswer + "%\n" + "C: " + otherAnswer2
								+ "%\n" + "D: " + otherAnswer3 + "%";
					else if (trueAns.equals("C"))
						guestAns = "A: " + otherAnswer1 + "%\n" + "B: "
								+ otherAnswer2 + "%\n" + "C: " + trueAnswer
								+ "%\n" + "D: " + otherAnswer3 + "%";
					else
						guestAns = "A: " + otherAnswer1 + "%\n" + "B: "
								+ otherAnswer2 + "%\n" + "C: " + otherAnswer3
								+ "%\n" + "D: " + trueAnswer + "%";
				} else {
					if (tmpReward < 5) {
						trueAnswer = new Random()
								.nextInt(percentGetTrueAnswerLevel1_2_To
										- percentGetTrueAnswerLevel1_2_From + 1)
								+ percentGetTrueAnswerLevel1_From;
					} else if (tmpReward < 10) {
						trueAnswer = new Random()
								.nextInt(percentGetTrueAnswerLevel2_2_To
										- percentGetTrueAnswerLevel2_2_From + 1)
								+ percentGetTrueAnswerLevel2_From;
					} else if (tmpReward < 15) {
						trueAnswer = new Random()
								.nextInt(percentGetTrueAnswerLevel3_2_To
										- percentGetTrueAnswerLevel3_2_From + 1)
								+ percentGetTrueAnswerLevel3_From;
					}

					otherAnswer1 = 100 - trueAnswer;

					String falseAns1 = listBtnAnswer.get(removeBtn1).getText()
							.toString().split("\\.")[0];
					String falseAns2 = listBtnAnswer.get(removeBtn2).getText()
							.toString().split("\\.")[0];

					if (trueAns.equals("A")) {
						if ((falseAns1 == "B" && falseAns2 == "C")
								|| (falseAns1 == "C" && falseAns2 == "B"))
							guestAns = "A: " + trueAnswer + "%\n" + "B: 0%\n"
									+ "C: 0%\n" + "D: " + otherAnswer1 + "%";
						else if ((falseAns1 == "B" && falseAns2 == "D")
								|| (falseAns1 == "D" && falseAns2 == "B"))
							guestAns = "A: " + trueAnswer + "%\n" + "B: 0%\n"
									+ "C: " + otherAnswer1 + "%\n" + "D: 0%";
						/*
						 * else if ((falseAns1 == "C" && falseAns2 == "D") ||
						 * (falseAns1 == "D" && falseAns2 == "C"))
						 */
						else
							guestAns = "A: " + trueAnswer + "%\n" + "B: "
									+ otherAnswer1 + "%\n" + "C: 0%\n"
									+ "D: 0%";
					} else if (trueAns.equals("B")) {
						if ((falseAns1 == "A" && falseAns2 == "C")
								|| (falseAns1 == "C" && falseAns2 == "A"))
							guestAns = "A: 0%\n" + "B: " + trueAnswer + "%\n"
									+ "C: 0%\n" + "D: " + otherAnswer1 + "%";
						else if ((falseAns1 == "A" && falseAns2 == "D")
								|| (falseAns1 == "D" && falseAns2 == "A"))
							guestAns = "A: 0%\n" + "B: " + trueAnswer + "%\n"
									+ "C: " + otherAnswer1 + "%\n" + "D: 0%";
						/*
						 * else if ((falseAns1 == "C" && falseAns2 == "D") ||
						 * (falseAns1 == "D" && falseAns2 == "C"))
						 */
						else
							guestAns = "A: " + otherAnswer1 + "%\n" + "B: "
									+ trueAnswer + "%\n" + "C: 0%\n" + "D: 0%";
					} else if (trueAns.equals("C")) {
						if ((falseAns1 == "A" && falseAns2 == "B")
								|| (falseAns1 == "B" && falseAns2 == "A"))
							guestAns = "A: 0%\n" + "B: 0%\n" + "C: "
									+ trueAnswer + "%\n" + "D: " + otherAnswer1
									+ "%";
						else if ((falseAns1 == "A" && falseAns2 == "D")
								|| (falseAns1 == "D" && falseAns2 == "A"))
							guestAns = "A: 0%\n" + "B: " + otherAnswer1 + "%\n"
									+ "C: " + trueAnswer + "%\n" + "D: 0%";
						/*
						 * else if ((falseAns1 == "B" && falseAns2 == "D") ||
						 * (falseAns1 == "D" && falseAns2 == "D"))
						 */
						else
							guestAns = "A: " + otherAnswer1 + "%\n" + "B: 0%\n"
									+ "C: " + trueAnswer + "%\n" + "D: 0%";
					} else {
						if ((falseAns1 == "A" && falseAns2 == "B")
								|| (falseAns1 == "B" && falseAns2 == "A"))
							guestAns = "A: 0%\n" + "B: 0%\n" + "C: "
									+ otherAnswer1 + "%\n" + "D: " + trueAnswer
									+ "%";
						else if ((falseAns1 == "A" && falseAns2 == "C")
								|| (falseAns1 == "C" && falseAns2 == "A"))
							guestAns = "A: 0%\n" + "B: " + otherAnswer1 + "%\n"
									+ "C: 0%\n" + "D: " + trueAnswer + "%";
						/*
						 * else if ((falseAns1 == "C" && falseAns2 == "D") ||
						 * (falseAns1 == "D" && falseAns2 == "C"))
						 */
						else
							guestAns = "A: " + otherAnswer1 + "%\n" + "B: 0%\n"
									+ "C: 0%\n" + "D: " + trueAnswer + "%";
					}
				}

				Toast.makeText(getApplicationContext(), guestAns,
						Toast.LENGTH_LONG).show();
				btnAskGuest.setVisibility(View.INVISIBLE);
			}
		});

		btnStopGame.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				counter.cancel();
				if (player_clock != null) {
					player_clock.stop();
				}

				AlertDialog infoDialog = createFinalDialog(
						"",
						"Bạn đã chọn giải pháp ngừng cuộc chơi để bảo toàn số điểm, phần thưởng bạn nhận được trị giá "
								+ lblCurTotalAmount.getText().toString()
								+ " VNĐ. Xin chúc mừng!!!");
				infoDialog.show();
				btnStopGame.setVisibility(View.VISIBLE);
			}
		});
	}

	private void firstGenReward() {
		listLblReward.add(R.id.lblReward1);
		listLblReward.add(R.id.lblReward2);
		listLblReward.add(R.id.lblReward3);
		listLblReward.add(R.id.lblReward4);
		listLblReward.add(R.id.lblReward5);
		listLblReward.add(R.id.lblReward6);
		listLblReward.add(R.id.lblReward7);
		listLblReward.add(R.id.lblReward8);
		listLblReward.add(R.id.lblReward9);
		listLblReward.add(R.id.lblReward10);
		listLblReward.add(R.id.lblReward11);
		listLblReward.add(R.id.lblReward12);
		listLblReward.add(R.id.lblReward13);
		listLblReward.add(R.id.lblReward14);
		listLblReward.add(R.id.lblReward15);

		if (lblRewardTmp == null || tmpReward == -1)
			tmpReward = 0;
		else
			tmpReward++;
		lblRewardTmp = (TextView) findViewById(listLblReward.get(tmpReward));
		lblRewardTmp.setBackgroundColor(Color.rgb(249, 219, 129));
		lblCurTotalAmount.setText("0");
	}

	private void genQuestion() {
		DBManager dbManager = new DBManager(getApplicationContext());

		List<Question> listQuestion = new ArrayList<Question>();

		if (tmpReward == -1) {
			listQuestion = dbManager.getQuestionsByLevel(1);
		} else {
			if (tmpReward < 5) {
				listQuestion = dbManager.getQuestionsByLevel(1);
			} else if (tmpReward < 10) {
				listQuestion = dbManager.getQuestionsByLevel(2);
			} else {
				listQuestion = dbManager.getQuestionsByLevel(3);
			}
		}

		for (Iterator<Question> it = listQuestion.iterator(); it.hasNext();) {
			Question question = it.next();
			if (listQuestionUsed.contains(question.getId())) {
				it.remove();
			}
		}

		// listQuestion.removeAll(listQuestionUsed);
//		Toast.makeText(getApplicationContext(),
//				listQuestion.size() + " - " + listQuestionUsed.size(),
//				Toast.LENGTH_LONG).show();

		Question curQuestion = listQuestion.get(new Random()
				.nextInt(listQuestion.size()));

		listQuestionUsed.add(curQuestion.getId());

		lblQuestion.setText(curQuestion.getContent());

		List<Answer> listAnswer = dbManager.getAnswersByQuestion(curQuestion
				.getId());

		Collections.shuffle(listAnswer);
		for (int i = 0; i < listAnswer.size(); i++) {
			listBtnAnswer.get(i).setText(listAnswer.get(i).getContent());
			if (listAnswer.get(i).getIsRight() == 1)
				tmpTrueAnswer = listBtnAnswer.get(i).getId();
		}

		boolean isTest = prefs.getBoolean("checkbox_gamemode", true);
		if (isTest)
			tmpTrueAnswer = R.id.btnAnswerA;

		btnAnswerA.setText("A. " + btnAnswerA.getText().toString());
		btnAnswerB.setText("B. " + btnAnswerB.getText().toString());
		btnAnswerC.setText("C. " + btnAnswerC.getText().toString());
		btnAnswerD.setText("D. " + btnAnswerD.getText().toString());
	}

	private void trueAnswer() {
		lblCurTotalAmount.setText(lblRewardTmp.getText());

		if (removeBtn1 != -1 && removeBtn2 != -1) {
			listBtnAnswer.get(removeBtn1).setVisibility(View.VISIBLE);
			listBtnAnswer.get(removeBtn2).setVisibility(View.VISIBLE);
		}

		if (tmpReward == listLblReward.size() - 1) {
			// end game
			counter.cancel();
			AlertDialog infoDialog = createFinalDialog("",
					"Chúc mừng bạn đã chiến thắng, bạn nhận được giải thưởng trị giá "
							+ lblCurTotalAmount.getText().toString() + " VNĐ.");
			infoDialog.show();
		} else {
			lblRewardTmp.setBackgroundColor(Color.TRANSPARENT);
			tmpReward++;
			lblRewardTmp = (TextView) findViewById(listLblReward.get(tmpReward));
			lblRewardTmp.setBackgroundColor(Color.rgb(249, 219, 129));

			genQuestion();
		}
	}

	private void falseAnswer() {
		counter.cancel();

		String finalTotalAmount = "0";
		double finalTotalReward = 0;
		if (!lblCurTotalAmount.getText().equals("0"))
			finalTotalReward = Double.valueOf(lblCurTotalAmount.getText()
					.toString().replace(".", "")) / 2;

		NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
		finalTotalAmount = format.format(finalTotalReward).split("\\.")[0]
				.replace(",", ".").replace("$", "");

		AlertDialog infoDialog = createFinalDialog("",
				"Rất tiếc bạn đã trả lời sai, số tiền bạn nhận được là "
						+ finalTotalAmount
						+ " VNĐ. Rất cám ơn bạn đã tham gia chương trình!");
		infoDialog.show();
	}

	private void playMusic(int music_id) {
		if (prefs.getBoolean("checkbox_sound", true)) {
			player = MediaPlayer.create(this, music_id);
			player.setLooping(false);
			player.setVolume(100, 100);
			player.start();
		}
	}

	private void initCountDownTimer() {
		lblCountDown.setText(playerTime + ":00");

		counter = new MyCount(playerTime * 60 * 1000, 1000);
		counter.start();
	}

	public class MyCount extends CountDownTimer {
		public MyCount(long millisecondInFuture, long countDownInterval) {
			super(millisecondInFuture, countDownInterval);
		}

		@Override
		public void onFinish() {
			lblCountDown.setText("00:00");

			String finalTotalAmount = "0";
			double finalTotalReward = 0;
			if (!lblCurTotalAmount.getText().equals("0"))
				finalTotalReward = Double.valueOf(lblCurTotalAmount.getText()
						.toString().replace(".", "")) / 2;

			NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
			finalTotalAmount = format.format(finalTotalReward).split("\\.")[0]
					.replace(",", ".").replace("$", "");

			AlertDialog infoDialog = createFinalDialog("",
					"Hết giờ, số tiền bạn nhận được là " + finalTotalAmount
							+ " VNĐ. Rất cám ơn bạn đã tham gia chương trình!");
			infoDialog.show();

			if (player_clock != null) {
				player_clock.stop();
			}
			if (prefs.getBoolean("checkbox_sound", true)) {
				playMusic(R.drawable.music_end);
			}
		}

		@Override
		public void onTick(long millisecondUntilFinished) {
			String[] tmpTime = lblCountDown.getText().toString().split(":");

			if (tmpTime[1].equals("00")) {
				tmpTime[0] = String.valueOf(Integer.valueOf(tmpTime[0]) - 1);
				tmpTime[1] = "59";
			}
			tmpTime[1] = String.valueOf(Integer.valueOf(tmpTime[1]) - 1);

			if (tmpTime[0].length() == 1)
				tmpTime[0] = "0" + tmpTime[0];
			if (tmpTime[1].length() == 1)
				tmpTime[1] = "0" + tmpTime[1];

			if (tmpTime[0].equals("00"))
				lblCountDown.setTextColor(Color.RED);

			lblCountDown.setText(tmpTime[0] + ":" + tmpTime[1]);
		}
	}

	private AlertDialog createFinalDialog(String title, String content) {
		AlertDialog infoDialog = new AlertDialog.Builder(this)
				.setIcon(R.drawable.logo)
				.setTitle(title)
				.setMessage(content)
				.setPositiveButton("Đóng",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								finish();
							}
						}).create();
		return infoDialog;
	}
}
